<?php
function proxy($url) {
	if (!$url) {
		// Passed url not specified.
		$contents = 'ERROR: url not specified';
		$status = array('http_code' => 'ERROR');
	} else {
		$ch = curl_init($url);

		if (strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $_POST);
		}

		$cookie = array();
		foreach ($_COOKIE as $key => $value) {
			$cookie[] = $key . '=' . $value;
		}
		$cookie = implode('; ', $cookie);

		$headers = array();
		foreach ($_SERVER as $key => $value) {
			if (strncmp($key, "HTTP_", 5) == 0) {
				$headers[substr($key, 5)] = $value;
			}
		}

		curl_setopt($ch, CURLOPT_COOKIE, $cookie);

		curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

		curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);

		list($header, $contents) = preg_split('/([\r\n][\r\n])\\1/', curl_exec($ch), 2);

		$status = curl_getinfo($ch);
		curl_close($ch);
	}

	// Split header text into an array.
	$header_text = preg_split('/[\r\n]+/', $header);

	// Propagate headers to response.
	foreach ($header_text as $header) {
		if (preg_match('/^(?:ETag|Expires|Last-Modified|Date|Content-Type|Content-Language|Set-Cookie):/i', $header)) {
			header($header);
		} else {
			header($header);
			// echo $header . "<br/>";
		}
	}

	header("Access-Control-Allow-Origin:*");

	if (empty($contents)) {
		$contents = file_get_contents($url);
	}
	echo $contents;
}